﻿using Common.Result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Common.MyCustomException;

namespace TakeawayWebApi.Controllers.Filter
{
    public class CustomerExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<CustomerExceptionFilter> _logger;
        public CustomerExceptionFilter(ILogger<CustomerExceptionFilter> logger)
        {
            _logger = logger;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            var exception = context.Exception;
            //将异常输出至日志
            _logger.LogError(exception.Message);
            //如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false) {
                #region 数据库唯一键冲突异常
                //序列化 result 类的属性转换成首字母小写
                var serializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }
                };
                //数据库唯一键冲突异常
                if (exception is SqlException sqlEx && (sqlEx.Number == 2601 || sqlEx.Number == 2627))
                {
                    string msg = null;//错误信息
                    if (sqlEx.Message.Contains("重复键值"))
                    {
                        var split=sqlEx.Message.Split("。");
                        string pattern = @"\((.*?)\)"; // 匹配 () 中的内容
                        MatchCollection matches = Regex.Matches(split[1], pattern);
                        foreach (Match match in matches)
                        {
                            msg = match.Groups[1].Value; // 获取第一个捕获组的值
                            //Console.WriteLine(result); // 输出 admin 和 test
                        }
                    }
                    var result = ResultHelper.Error(msg+"已存在");
                    var json = JsonConvert.SerializeObject(result, serializerSettings);
                    context.Result = new ContentResult
                    {
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "application/json;charset=utf-8",
                        Content = json
                    };
                }
                #endregion
                #region 自定义业务异常
                else if (exception is MyCustomException)
                {
                    //其他异常
                    var result = ResultHelper.Error(exception.Message);
                    var json = JsonConvert.SerializeObject(result, serializerSettings);
                    context.Result = new ContentResult
                    {
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "application/json;charset=utf-8",
                        Content = json
                    };
                }
                #endregion
                else
                {
                    //其他异常
                    var result = ResultHelper.Error("服务器繁忙，请稍后重试");
                    var json = JsonConvert.SerializeObject(result, serializerSettings);
                    context.Result = new ContentResult
                    {
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "application/json;charset=utf-8",
                        Content = json
                    };
                }
            }
            //表示异常已被处理
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
